package com.pms.utils;

import java.text.DecimalFormat;

public class DoubleUtility {

	/**
	 * valid comparison results
	 */
	public static final int EQUAL = 0;

	public static final int LESS_THAN = -1;

	public static final int GREATER_THAN = 1;

	public static final double mEpsilon = 0.0001;

	/**
	 * Performs double comparisons suitable for comparing monetary amounts. i.e.
	 * it ignores differences of less than 4 decimal points.
	 * 
	 * @param double
	 * @param double
	 * 
	 * @return 1 - GREATER_THAN - if the first double is greater 0 - EQUAL - if
	 *         they are equal -1 - LESS_THAN - if the first double is smaller
	 */
	public static int compare(double aDouble1, double aDouble2) {

		int result;

		if ((aDouble1 - aDouble2) > mEpsilon) {
			result = GREATER_THAN;
		} else if ((aDouble2 - aDouble1) > mEpsilon) {
			result = LESS_THAN;
		} else {
			result = EQUAL;
		}

		return result;
	}

	/**
	 * Retruns the absolute difference of two double amounts. i.e. we ignore
	 * differences of less than 4 decimal points.
	 * 
	 * @param double
	 * @param double
	 * 
	 * @return double - the difference as a positive double
	 */
	public static double absoluteDifference(double aDouble1, double aDouble2) {

		double difference = aDouble1 - aDouble2;

		if (difference < 0)
			difference *= -1;

		if (difference < mEpsilon)
			difference = 0;

		return difference;
	}

	/**
	 * If a double is zero to decimal places, this method ensures it has a
	 * positive sign so formatters don't display '-0.00' .
	 * 
	 * @param double
	 * 
	 * @return double - the converted double
	 */
	public static double makeZeroPositive(double aDouble) {

		if (compare(aDouble, 0.00) == EQUAL) {
			aDouble = 0.00;
		}

		return aDouble;
	}
	
	
    public static String formatToString(double value) {
        DecimalFormat twoPlaces = new DecimalFormat("0.00");
        String result = twoPlaces.format(value);
        return result;
    }
	    
	
}